﻿/**********************************************************************
*创建人：蔡水明
*创建时间：2018/2/21 19:38:03
*说明：<Function>
/**********************************************************************/
using SharpCompress.Readers;
using System;
using System.IO;

namespace Utilities
{
    /// <summary>
    /// 自动更新类
    /// </summary>
    public class AutoUpdateHelper
    {
        #region 内部变量
        /// <summary>
        /// 自动更新的本地临时文件
        /// </summary>
        private string AutoUpdateLocalRarfile = string.Empty;
        /// <summary>
        /// 自动更新的本地临时文件夹
        /// </summary>
        private string AutoUpdateLocalDir = string.Empty;
        /// <summary>
        /// 自动更新的Exe程序名称
        /// </summary>
        private const string AutoUpdateExe = "AutoUpdater.exe";
        /// <summary>
        /// AutoUpdate使用的target.txt文件（记录要复制的目标文件夹）
        /// </summary>
        private const string TargetFile = "updateInfo.txt";        
        /// <summary>
        /// 本地版本号
        /// </summary>
        private string LocalVer { get; set; }
        /// <summary>
        /// 远程版本号
        /// </summary>
        private string RemoteVer { get; set; }
        private FtpHelper ftpInfo { get; set; }
        /// <summary>
        /// 更新描述
        /// </summary>
        private string UpdateDescript { get; set; }
        public string MainExecFile { get; set; }
        #endregion
        /// <summary>
        /// 自动更新
        /// </summary>
        /// <param name="localVer">本地版本号</param>
        /// <param name="remoteVer">远程版本号</param>
        /// <param name="Descript">描述</param>
        /// <param name="ExecFile">exe(自己)</param>
        /// <param name="localDir">下载及解压的更新临时文件</param>
        /// <param name="ftp">ftp服务器</param>
        public AutoUpdateHelper(string localVer,string remoteVer,string Descript,string ExecFile,string localDir,FtpHelper ftp)
        {
            LocalVer = localVer;
            RemoteVer = remoteVer;
            UpdateDescript = Descript;
            ftpInfo = ftp;
            MainExecFile = ExecFile;

            string localFile = "Updaters.rar";
            if (!Directory.Exists(localDir)) Directory.CreateDirectory(localDir);
            //AutoUpdateLocalRarfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Templates), localFile);
            AutoUpdateLocalRarfile = Path.Combine(localDir, localFile);

            string extDir = "Updaters";
            //AutoUpdateLocalDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Templates), extDir);
            AutoUpdateLocalDir = Path.Combine(localDir, extDir);
            

            ftpInfo.LocalFile=AutoUpdateLocalRarfile;
        }
        /// <summary>
        /// 检查并更新
        /// </summary>
        public bool CheckAndUpdate()
        {
            Version lVer = new Version(LocalVer);
            if (lVer.CompareTo(new Version(RemoteVer)) < 0)//发现新版本
            {
                if (ftpInfo.DownLoadFile())//下载rar文件
                {
                    if (!ExtRar()) return false;//解压缩
                    string AutoUpdateFullFile = GetAutoUpdateExe();//找到AutoUpdate.exe   
                    if (string.IsNullOrEmpty(AutoUpdateFullFile)) return false;                 
                    string AutoUpdateDir = Path.GetDirectoryName(AutoUpdateFullFile);
                    try
                    {
                        File.Delete(AutoUpdateLocalRarfile);//删除RAR文件                        
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                    }
                    string updateString = Environment.CurrentDirectory+Environment.NewLine;
                    updateString+=MainExecFile + Environment.NewLine;
                    updateString+=UpdateDescript + Environment.NewLine;
                    updateString += RemoteVer;
                    TxtHelper.StringToFile(updateString, Path.Combine(AutoUpdateDir, TargetFile));//把当前文件所在位置写入txt文件，方便AutoUpdater.exe调用
                    var p = new System.Diagnostics.Process();//打开AutoUpdater.exe
                    p.StartInfo.FileName = AutoUpdateFullFile;
                    p.StartInfo.WorkingDirectory = Path.GetDirectoryName(AutoUpdateFullFile);
                    p.Start();
                    return true;
                }
            }
            return false;

        }
        /// <summary>
        /// 搜索AutoUpdate.exe文件
        /// </summary>
        /// <returns></returns>
        private string GetAutoUpdateExe()
        {
            DirectoryInfo dir = new DirectoryInfo(AutoUpdateLocalDir);
            foreach (FileInfo item in dir.GetFiles(AutoUpdateExe, SearchOption.AllDirectories))
            {
                return item.FullName;
            }
            return "";
        }
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <returns></returns>
        private bool ExtRar()
        {
            using (Stream stream = File.OpenRead(AutoUpdateLocalRarfile))
            {
                var reader = ReaderFactory.Open(stream);

                if (Directory.Exists(AutoUpdateLocalDir))
                {
                    try
                    {
                        Directory.Delete(AutoUpdateLocalDir, true);
                    }
                    catch (Exception ex)
                    {
                        Utilities.LogHelper.Error(ex);
                    }

                }
                Directory.CreateDirectory(AutoUpdateLocalDir);
                reader.WriteAllToDirectory(AutoUpdateLocalDir, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
            }
            return true;
        }
    }
}
